package com.htfyun.roobofactory;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.htfyun.roobofactory.config.PCCommand;
import com.htfyun.roobofactory.config.RooboBuildConfig;
import com.htfyun.roobofactory.factorytest.FactoryTestItemsEnum;
import com.htfyun.roobofactory.htfyunUtils.FTFloatUtils;
import com.htfyun.roobofactory.htfyunUtils.NvDataTool;
import com.htfyun.roobofactory.utils.FileReadWrite;
import com.htfyun.roobofactory.utils.PermissionManager;
import com.roobo.common.utils.Utils;
import com.roobo.hardware.RockChipSn;

/**
 * Created by sst on 2018/7/25.
 */

public class PCCommandHandleActivity extends Activity {

    private final static String TAG = PCCommandReceiver.TAG;

    private Activity mActivity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_pc_command_activity);

        mActivity = this;

        initPermission();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "pc command destroy");
    }

    private Activity getActivity() {
        return mActivity;
    }

    private void initPermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            //同时申请多个权限
            PermissionManager.getInstance(getApplicationContext()).execute(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE

            );

        } else {

            tryHandleAction();

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.getInstance(getApplicationContext()).
                onRequestPermissionsResult(requestCode, permissions, grantResults);

        Log.e(TAG, "pc command ~~~~~~~~~~~~~~onRequestPermissionsResult");

        tryHandleAction();

    }

    private void tryHandleAction() {

        Intent intent = getIntent();
        if (null == intent) {
            ActivityCompat.finishAfterTransition(getActivity());
            return;
        }
        String action = intent.getAction();
        handleAction(this, action);

        ActivityCompat.finishAfterTransition(getActivity());

    }

    private void handleAction(Context context, String action) {

        if (action == null) {
            return;
        }

        if (action.equals(PCCommand.PC_ACTION_GET_RESULT_PCBA)) {

            String result = NvDataTool.getInstance().getPCBAResult();

            Log.e(TAG, "pcba result = " + result);

            int flag = NvDataTool.getInstance().getCX20921DownloadFlag();

            Log.e(TAG, "cx20921 flag = " + Integer.toHexString(flag));

            if (result == null) {
                result = "";
            }

            if (RooboBuildConfig.FT_FORCE_PCBA_PASSED) {
                result = "pass 1234567890";//pc tool 检测字符长度 >10, 没有 MA, fail
                Log.e(TAG, "force pcba passed, result = " + result);
            }

            FileReadWrite.writeStringToFile(PCCommand.PC_ACTION_GET_RESULT_PCBA_FILE_PATH, result);

        } else if (action.equals(PCCommand.PC_ACTION_GET_FT_CHECKED_AND_RESULT)) {

            String val = PCCommand.PC_TOOL_FT_UNCHECKED;

            if (NvDataTool.getInstance().isFactoryTestChecked()) {
                val = PCCommand.PC_TOOL_FT_CHECKED;
            }

            FileReadWrite.writeStringToFile(PCCommand.PC_ACTION_GET_FT_CHECKED_AND_RESULT_CHECKED_FILE_PATH, val);

            //write result
            String sn = RockChipSn.getInstance().getSN();
            String bsn = RockChipSn.getInstance().getBSN();
            String mac = RockChipSn.getInstance().getWifiMac();


            if (RooboBuildConfig.FT_FORCE_ALL_TEST_ITEMS_PASSED) {

                /**
                 * 1015020000000047,000104170306000041,AC:83:F3:5D:78:86,
                 * LCD pass,TP pass,camera pass,外放 pass,MIC pass,光感 pass,距感 pass,
                 * KEY pass,MOTO pass,LED pass,充电 pass,SDcard pass
                 */
                StringBuilder passSB = new StringBuilder("");
                passSB.append(sn);
                passSB.append(",");
                passSB.append(bsn);
                passSB.append(",");
                passSB.append(mac);
                passSB.append(",");
                String pass1 = "LCD pass";
                passSB.append(pass1);
                passSB.append(",");
                passSB.append(pass1);
                passSB.append(",");
                passSB.append(pass1);
                passSB.append(",");
                passSB.append(pass1);

                Log.e(TAG, "FT_FORCE_ALL_TEST_ITEMS_PASSED pass = " + passSB.toString());
                FileReadWrite.writeStringToFile(PCCommand.PC_ACTION_GET_FT_CHECKED_AND_RESULT_RESULT_FILE_PATH, passSB.toString());


                String log = "FT_FORCE_ALL_TEST_ITEMS_PASSED : this is a log ";//length > 10 即可
                FileReadWrite.writeStringToFile(PCCommand.PC_ACTION_GET_FT_CHECKED_AND_RESULT_LOG_FILE_PATH, log);


            } else {

                StringBuilder sb = new StringBuilder("");
                sb.append(sn);
                sb.append(",");
                sb.append(bsn);
                sb.append(",");
                sb.append(mac);
                sb.append(",");

                int size = 0;
                for (FactoryTestItemsEnum itemsEnum : FactoryTestItemsEnum.values()) {
                    sb.append(context.getString(itemsEnum.getNameEnResId()));
                    sb.append(" ");
                    sb.append(itemsEnum.getResult(context));

                    size++;

                    if (size != FactoryTestItemsEnum.values().length) {
                        sb.append(",");
                    }
                }

                FileReadWrite.writeStringToFile(PCCommand.PC_ACTION_GET_FT_CHECKED_AND_RESULT_RESULT_FILE_PATH, sb.toString());
                Log.e(TAG, "result = " + sb.toString());

                StringBuilder logSB = new StringBuilder("");
                for (FactoryTestItemsEnum itemsEnum : FactoryTestItemsEnum.values()) {
                    logSB.append(context.getString(itemsEnum.getNameEnResId()));
                    logSB.append("->");
                    logSB.append(itemsEnum.getLog(context));
                    logSB.append(";");
                }
                Log.e(TAG, "log = " + logSB.toString());

                FileReadWrite.writeStringToFile(PCCommand.PC_ACTION_GET_FT_CHECKED_AND_RESULT_LOG_FILE_PATH, logSB.toString());

            }

        } else if (action.equals(PCCommand.PC_ACTION_SET_CHECKED)) {

            FileReadWrite.writeStringToFile(PCCommand.PC_ACTION_GET_FT_CHECKED_AND_RESULT_CHECKED_FILE_PATH, PCCommand.PC_TOOL_FT_CHECKED);
            NvDataTool.getInstance().setFactoryCheck(true);
            Utils.setSystemProperty(PCCommand.PC_ACTION_SET_CHECKED_PROP, PCCommand.PC_TOOL_FT_CHECKED);

            FTFloatUtils.stopFTFloat(context);

        } else if (action.equals(PCCommand.PC_ACTION_SET_UNCHECKED)) {

            FileReadWrite.writeStringToFile(PCCommand.PC_ACTION_GET_FT_CHECKED_AND_RESULT_CHECKED_FILE_PATH, PCCommand.PC_TOOL_FT_UNCHECKED);
            NvDataTool.getInstance().setFactoryCheck(false);
            Utils.setSystemProperty(PCCommand.PC_ACTION_SET_CHECKED_PROP, PCCommand.PC_TOOL_FT_UNCHECKED);

            startMainActivity(context);
        }
    }

    private void startMainActivity(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
